//
//  AppointmentAndAvailbilityViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 12/31/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class AppointmentAndAvailabilityViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    @IBOutlet weak var dateLabel:UILabel!;
    @IBOutlet weak var tableView:UITableView!;
    
    
    var groupButton:UIButton!;
    // selectedSegmentIndex  0. availabilities 1. appointments
    var tabControl:UISegmentedControl!;
    var createAppointmentButton:UIButton!;
    
    var groupPicker:GroupPicker!;
    var notFoundLabel:UILabel!;
    
    var date:NSDate = DateUtils.now();
    var availabilities:[NSDictionary] = [];
    var appointments:[NSDictionary] = [];
    
    override func viewDidLoad() {
        super.viewDidLoad();
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.addGestureRecognizer();
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.showTabBar();
        self.addNavigationItem();
        self.initGroupPicker();
        self.initNotFoundLabel();
        
        var selectedSegmentIndex = tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            self.appointments = [];
            self.loadAvailabilities();
        } else {
            self.availabilities = [];
            self.loadAppointments();
        }
    }
    
    func addNavigationItem(){
        if(self.tabControl == nil){
            var margin:CGFloat = 16;
            self.groupButton = UIButton();
            self.groupButton.setTitle("我的好友", forState: UIControlState.Normal);
            self.groupButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
            self.groupButton.titleLabel?.font = Utils.defaultFont();
            self.groupButton.addTarget(self, action: Selector("choiceGroup:"), forControlEvents: UIControlEvents.TouchUpInside);
            self.groupButton.sizeToFit();
            var groupButtonOriginY = (self.navBarHeight()! - self.groupButton.frame.height) / 2;
            self.groupButton.frame.origin = CGPoint(x: margin, y: groupButtonOriginY);
            self.navigationController?.navigationBar.addSubview(self.groupButton);
            
            self.createAppointmentButton = UIButton();
            self.createAppointmentButton.setImage(UIImage(named: "add"), forState: UIControlState.Normal);
            self.createAppointmentButton.showsTouchWhenHighlighted = true;
            self.createAppointmentButton.sizeToFit();
            self.createAppointmentButton.addTarget(self, action: Selector("createAppointment:"), forControlEvents: UIControlEvents.TouchUpInside);
            var createAppointmentButtonOriginX = self.navigationController!.navigationBar.frame.width - self.createAppointmentButton.frame.width - margin;
            var createAppointmentButtonOriginY = (self.navBarHeight()! - self.createAppointmentButton.frame.height) / 2;
            self.createAppointmentButton.frame.origin = CGPoint(x: createAppointmentButtonOriginX, y: createAppointmentButtonOriginY);
            self.navigationController?.navigationBar.addSubview(self.createAppointmentButton);
            
            
            self.tabControl = UISegmentedControl(items: ["空余时间","约球安排"]);
            var attributes = [NSFontAttributeName:Utils.defaultFont(),NSForegroundColorAttributeName:UIColor.whiteColor()];
            self.tabControl.setTitleTextAttributes(attributes, forState: UIControlState.Normal);
            self.tabControl.selectedSegmentIndex = 0;
            self.tabControl.highlighted = true;
            self.tabControl.sizeToFit();
            var tabControlOriginX = (self.groupButton.frame.width + margin) + (self.view.frame.width - (self.groupButton.frame.width + margin) - (self.createAppointmentButton.frame.width + margin) - self.tabControl.frame.width) / 2;
            var tabContolOriginY = (self.navBarHeight()! - self.tabControl.frame.height) / 2;
            self.tabControl.frame.origin = CGPoint(x: tabControlOriginX, y: tabContolOriginY);
            self.tabControl.addTarget(self, action: Selector("toggleTab:"), forControlEvents: UIControlEvents.ValueChanged);
            self.navigationController?.navigationBar.addSubview(self.tabControl);
        }
        
        self.groupButton.hidden = false;
        self.tabControl.hidden = false;
        self.createAppointmentButton.hidden = false;
    }
    
    func initGroupPicker(){
        if(self.groupPicker == nil){
            var frame = CGRect(x: 0, y: self.view.frame.height / 2, width: self.view.frame.width, height: self.view.frame.height / 2);
            self.groupPicker = GroupPicker(frame: frame);
            self.groupPicker.addTarget(self, action: Selector("groupPickerValueChange:"), forControlEvents: UIControlEvents.ValueChanged);
            self.tabBarController!.view.addSubview(self.groupPicker);
        }
    }
    
    
    func initNotFoundLabel(){
        if(self.notFoundLabel == nil){
            self.notFoundLabel = UILabel();
            self.notFoundLabel.frame.origin = CGPoint(x: 0, y: 0);
            self.notFoundLabel.font = Utils.defaultFont();
            self.notFoundLabel.textColor = UIColor.whiteColor();
            self.notFoundLabel.textAlignment = NSTextAlignment.Center;
        }
    }
    
    func choiceGroup(sender: UIButton) {
        self.groupPicker.show();
    }
    
    func toggleTab(tabControl:UISegmentedControl){
        var selectedSegmentIndex = tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            var isBeforeToday = DateUtils.isBeforeToday(self.date);
            if(isBeforeToday){
                self.date = NSDate();
                self.updateDateLabel();
            }
            self.appointments = [];
            self.loadAvailabilities();
        } else {
            self.availabilities = [];
            self.loadAppointments();
        }
    }
    
    func addGestureRecognizer(){
        var leftGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("refreshAvailabilities:"));
        leftGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left;
        self.tableView.addGestureRecognizer(leftGestureRecognizer);
        
        var rightGuestureRecongnizer = UISwipeGestureRecognizer(target: self, action: Selector("refreshAvailabilities:"));
        rightGuestureRecongnizer.direction = UISwipeGestureRecognizerDirection.Right;
        self.tableView.addGestureRecognizer(rightGuestureRecongnizer);
    }
    
    func refreshAvailabilities(gestureRecognizer:UISwipeGestureRecognizer){
        self.tableView.editing = false;
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        var isAfterToday = DateUtils.isAfterToday(self.date);
        
        var direction = gestureRecognizer.direction;
        switch direction{
        case UISwipeGestureRecognizerDirection.Left:
            self.date = DateUtils.plusDays(date, days: 1);
            if(selectedSegmentIndex == 0){
                self.loadAvailabilities();
            } else {
                self.loadAppointments();
            }
            TransitionUtils.slideInFromRight(self.tableView);
            break;
        case UISwipeGestureRecognizerDirection.Right:
            if(isAfterToday && selectedSegmentIndex == 0){
                self.date = DateUtils.plusDays(date, days: -1);
                self.loadAvailabilities();
                 TransitionUtils.slideInFromLeft(self.tableView);
            }
            if(selectedSegmentIndex == 1){
                self.date = DateUtils.plusDays(date, days: -1);
                self.loadAppointments();
                 TransitionUtils.slideInFromLeft(self.tableView);
            }
           break;
        default:
            break;
        }
        
        self.updateDateLabel();
    }
    
    func updateDateLabel(){
        var resolvedDate = DateUtils.dateResolve(self.date);
        self.dateLabel.text = "\(resolvedDate)";
        self.dateLabel.sizeToFit();
    }
    
    // Load appointments
    func loadAppointments(){
        self.processing();
        var dateAsString = DateUtils.toString(self.date, format: "yyyy-MM-dd");
        var group = groupPicker.group;
        var groupGuid = group != nil ? group!.objectForKey("groupGuid") as String : "";
        var url = "/api/v1/appointments?date=\(dateAsString)&groupGuid=\(groupGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            
            self.appointments = response as [NSDictionary];
            if(self.appointments.count > 0){
                self.notFoundLabel.removeFromSuperview();
            } else {
                self.appointments = [];
                self.notFoundLabel.text = "没有日程安排";
                self.notFoundLabel.sizeToFit();
                self.notFoundLabel.frame.size.width = self.tableView.frame.width;
                self.tableView.addSubview(self.notFoundLabel);
            }
            self.tableView.editing = false;
            self.tableView.reloadData();
            self.processComplete();
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    // Load availabilities
    func loadAvailabilities(){
        self.processing();
        var dateAsString = DateUtils.toString(self.date, format: "yyyy-MM-dd");
        var group = self.groupPicker.group;
        var groupGuid = group != nil ? group!.objectForKey("groupGuid") as String : "";
        let url = "/api/v1/search/availability?date=\(dateAsString)&groupGuid=\(groupGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            self.availabilities = response as [NSDictionary];
            if(self.availabilities.count > 0){
                self.notFoundLabel.removeFromSuperview();
            } else {
                self.notFoundLabel.text = "小伙伴们都没空哦";
                self.notFoundLabel.sizeToFit();
                self.notFoundLabel.frame.size.width = self.tableView.frame.width;
                self.tableView.addSubview(self.notFoundLabel);
            }
            self.tableView.editing = false;
            self.tableView.reloadData();
            self.processComplete();
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    // Create appointment
    func createAppointment(sender:UIButton){
        var selectedAvailabilities:[NSDictionary] = [];
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            var cells = self.tableView.visibleCells() as [AvailablePersionalCell];
            for cell in cells{
                if(cell.checked){
                    selectedAvailabilities.append(cell.availability);
                }
            }
        }
        var storyboard = UIStoryboard(name: "Appointment", bundle: nil);
        var createAppointmentViewController = storyboard.instantiateViewControllerWithIdentifier("createAppointmentView") as CreateAppointmentViewController;
        createAppointmentViewController.appointmentDate(self.date);
        createAppointmentViewController.willInvitationPersons(selectedAvailabilities);
        self.navigationController?.pushViewController(createAppointmentViewController, animated: true);
    }
    
    
    func groupPickerValueChange(groupPicker:GroupPicker){
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            self.loadAvailabilities();
        } else {
            self.loadAppointments();
        }
        var group = self.groupPicker.group;
        if(group != nil){
            var groupName = group?.objectForKey("groupName") as String;
            self.groupButton.setTitle(groupName, forState: UIControlState.Normal);
        }
    }
    
    // Previous date
    @IBAction func previousDate(sender: UIButton) {
        self.tableView.editing = false;
        var selectedSegmentIndex = tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            let isAfterToday = DateUtils.isAfterToday(self.date);
            if(isAfterToday){
                self.date = DateUtils.plusDays(self.date, days: -1);
                self.loadAvailabilities();
            }
            
        } else {
            self.date = DateUtils.plusDays(self.date, days: -1);
            self.loadAppointments();
        }
        self.updateDateLabel();
    }
    
    // Next date
    @IBAction func nextDate(sender: UIButton) {
        self.tableView.editing = false;
        self.date = DateUtils.plusDays(self.date, days: 1);
        var selectedSegmentIndex = tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            self.loadAvailabilities();
        } else {
            self.loadAppointments();
        }
        self.updateDateLabel();
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            return self.availabilities.count;
        }
        return self.appointments.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 0){
            var available = self.availabilities[indexPath.row] as NSDictionary;
            var cell = AvailablePersionalCell();
            cell.setWidth(tableView.frame.width);
            cell.selectionStyle = UITableViewCellSelectionStyle.None;
            cell.setup(available);
            return cell;
        }
        var appointment = self.appointments[indexPath.row];
        var cell = AppointmentCell.create(indexPath,appointment: appointment,width:tableView.frame.width);
        cell.addAcceptInvitationCallback(acceptInvitationCallback);
        return cell;
    }
    
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 1){
            var appointment = self.appointments[indexPath.row];
            var creator = appointment.objectForKey("creator") as NSMutableDictionary;
            var creatorGuid = creator.objectForKey("guid") as String;
            var isOwner = Utils.isOwner(creatorGuid);
            var canOperationInvitation = appointment.objectForKey("canOperationInvitation") as Bool;
            var canSendJoinRequest = appointment.objectForKey("canSendJoinRequest") as Bool;
            if(isOwner || canOperationInvitation || canSendJoinRequest){
                return true;
            }
            return false;
        }
        return false;
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
        var appointment = self.appointments[indexPath.row];
        var appointmentGuid = appointment.objectForKey("guid") as String;
        var invitee = appointment.objectForKey("invitee") as Bool;
        if(invitee){
            var acceptInvitationAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
                self.acceptInvitationCallback(indexPath);
            })
            acceptInvitationAction.backgroundColor = UIColor(patternImage: UIImage(named: "ok_in_row")!);
            
            var rejectInvitationAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:rejectInvitaion);
            rejectInvitationAction.backgroundColor = UIColor(patternImage: UIImage(named: "close_in_row")!);
            return [rejectInvitationAction,acceptInvitationAction];
        }
        
        var canSendJoinRequest = appointment.objectForKey("canSendJoinRequest") as Bool;
        if(canSendJoinRequest){
            var sendJoinRequest = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
                self.sendJoinRequest(appointmentGuid);
            });
            sendJoinRequest.backgroundColor = UIColor(patternImage: UIImage(named: "add_in_row")!);
            return [sendJoinRequest];
        }
        
        var deleteAppointmentAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:deleteAppointment);
        deleteAppointmentAction.backgroundColor = UIColor(patternImage: UIImage(named: "close_in_row")!);
        return [deleteAppointmentAction];
    }
    
    // Send join appointment request
    func sendJoinRequest(appointmentGuid:String){
        var url = "/api/v1/appointment/request";
        var httpBody = NSMutableDictionary();
        httpBody.setObject(appointmentGuid, forKey: "appointmentGuid");
        self.processing();
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
            self.processComplete();
            UIAlertView(title: "请求发送成功", message: "已通知你的小伙伴了", delegate: self, cancelButtonTitle: "好的").show();
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    func acceptInvitationCallback(indexPath:NSIndexPath){
        var url = "/api/v1/appointment/accept";
        var appointment = self.appointments[indexPath.row];
        
        var appointmentGuid = appointment.objectForKey("guid") as String;
        var httpBody = NSMutableDictionary();
        httpBody.setObject(appointmentGuid, forKey: "guid");
        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
            self.updateTabBarBadge();
            self.loadAppointments()
            }, errorHandle: { (error) -> Void in
        });
    }
    
    func rejectInvitaion(action:UITableViewRowAction!, indexPath:NSIndexPath!){
        var url = "/api/v1/appointment/reject";
        var appointment = self.appointments[indexPath.row];
        var appointmentGuid = appointment.objectForKey("guid") as String;
        var httpBody = NSMutableDictionary();
        httpBody.setObject(appointmentGuid, forKey: "guid");
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
            self.updateTabBarBadge();
            self.loadAppointments();
            }, errorHandle: { (error) -> Void in
                
        });
    }
    
    func deleteAppointment(action:UITableViewRowAction!, indexPath:NSIndexPath!){
        ConfirmView(message: "确定删除此次约球?", confirm: { () -> Void in
            var appointment = self.appointments[indexPath.row];
            var guid = appointment.objectForKey("guid") as String;
            var url = "/api/v1/appointment";
            var httpBody = NSMutableDictionary();
            httpBody.setObject(guid, forKey: "guid");
            HttpUtils.sendRequest(url, method: RequestMethod.DELETE, httpBody: httpBody, successHandle: { (response) -> Void in
                self.appointments.removeAtIndex(indexPath.row)
                self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic);
                }, errorHandle: { (error) -> Void in
                    
            });
            }, cancel: nil).show();
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var selectedSegmentIndex = self.tabControl.selectedSegmentIndex;
        if(selectedSegmentIndex == 1){
            var appointment = appointments[indexPath.row] as NSMutableDictionary;
            var appointmentGuid = appointment.objectForKey("guid") as String;
            var creator = appointment.objectForKey("creator") as NSMutableDictionary;
            var creatorGuid = creator.objectForKey("guid") as String;
            var location = appointment.objectForKey("location") as String;
            var isOwner = Utils.isOwner(creatorGuid);
            var storyboard = UIStoryboard(name: "Appointment", bundle: nil);
            var viewController = storyboard.instantiateViewControllerWithIdentifier("appointmentDetailsView") as AppointmentDetailsController;
            viewController.setAppointmentGuid(appointmentGuid);
            self.navigationController?.pushViewController(viewController, animated: true);
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated);
        self.groupButton.hidden = true;
        self.tabControl.hidden = true;
        self.createAppointmentButton.hidden = true;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
        // Dispose of any resources that can be recreated.
    }
    
}
